package com.xyazm.common.core;

import com.xyazm.common.exception.BaseErrorCodeEnum;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.io.Serializable;

/**
 * 统一的Spring mvc响应结果封装对象
 */
@Slf4j
@Data
public class JsonResult<T> implements Serializable {

    private static final long serialVersionUID = 1L;

    /**
     * 请求失败
     */
    private static final String FAIL_CODE = "500";

    /**
     * 默认错误码
     */
    private static final String SUCCESS_CODE = "200";

    /**
     * 业务数据
     */
    private T data;

    /**
     * 错误码
     */
    private String code;

    /**
     * 错误提示语
     */
    private String message;


    public JsonResult() {
    }

    public JsonResult(T data, String errorCode, String errorMessage) {
        this.data = data;
        this.code = errorCode;
        this.message = errorMessage;
    }

    /**
     * 成功，不用返回数据
     *
     * @return
     */
    public static <T> JsonResult<T> buildSuccess() {
        return buildSuccess(null);
    }

    /**
     * 成功，返回数据
     *
     * @param data
     * @return
     */
    public static <T> JsonResult<T> buildSuccess(T data) {
        return new JsonResult<>(data, SUCCESS_CODE, "操作成功");
    }

    /**
     * 失败，固定状态码
     *
     * @param errorMsg
     * @return
     */
    public static <T> JsonResult<T> buildError(String errorMsg) {
        return new JsonResult<>(null, FAIL_CODE, errorMsg);
    }

    /**
     * 失败，自定义错误码和信息
     *
     * @param errorCode 错误码
     * @param errorMsg  错误提示
     * @return
     */
    public static <T> JsonResult<T> buildError(String errorCode, String errorMsg) {
        return new JsonResult<>(null, errorCode, errorMsg);
    }

    /**
     * 失败，枚举类定义错误码和信息
     *
     * @param baseErrorCodeEnum
     * @return
     */
    public static <T> JsonResult<T> buildError(BaseErrorCodeEnum baseErrorCodeEnum) {
        return new JsonResult<>(null, baseErrorCodeEnum.getErrorCode(), baseErrorCodeEnum.getErrorMsg());
    }


}
